/**
 * 名片管理系统JavaScript功能
 */
$(document).ready(function() {
    // 当前名片夹ID
    const folderId = $("#folderId").val();

    // 加载已删除的名片列表
    $("#deleted-tab").on("click", function() {
        loadDeletedCards();
    });

    function loadDeletedCards() {
        $.ajax({
            url: "/user/businesscard/card/search",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                folderId: folderId,
                isDeleted: true
            }),
            success: function(response) {
                if (response.success) {
                    renderDeletedCards(response.cards);
                } else {
                    $("#deletedCardsContainer").html('<div class="alert alert-danger">加载失败：' + response.message + '</div>');
                }
            },
            error: function() {
                $("#deletedCardsContainer").html('<div class="alert alert-danger">加载失败，请稍后重试</div>');
            }
        });
    }

    function renderDeletedCards(cards) {
        if (cards.length === 0) {
            $("#deletedCardsContainer").html(
                '<div class="text-center py-5">' +
                    '<i class="fa fa-trash-o" style="font-size: 4rem; color: #ccc;"></i>' +
                    '<p class="mt-3">回收站中没有已删除的名片</p>' +
                '</div>'
            );
            return;
        }

        let html = '<table class="table table-hover">' +
                   '<thead>' +
                   '<tr>' +
                   '<th>姓名</th>' +
                   '<th>性别</th>' +
                   '<th>联系电话</th>' +
                   '<th>机构名称</th>' +
                   '<th>职务</th>' +
                   '<th class="text-right">操作</th>' +
                   '</tr>' +
                   '</thead>' +
                   '<tbody>';

        cards.forEach(function(card) {
            html += '<tr>' +
                    '<td>' + (card.name || '') + '</td>' +
                    '<td>' + (card.gender || '') + '</td>' +
                    '<td>' + (card.phone || '') + '</td>' +
                    '<td>' + (card.organization || '') + '</td>' +
                    '<td>' + (card.position || '') + '</td>' +
                    '<td class="text-right card-actions">' +
                    '<button class="btn btn-sm btn-outline-primary btn-card-action restore-card" data-id="' + card.id + '" title="恢复">' +
                    '<i class="fa fa-undo"></i>' +
                    '</button> ' +
                    '<button class="btn btn-sm btn-outline-danger btn-card-action remove-card" data-id="' + card.id + '" data-name="' + (card.name || '') + '" title="彻底删除">' +
                    '<i class="fa fa-times"></i>' +
                    '</button>' +
                    '</td>' +
                    '</tr>';
        });

        html += '</tbody></table>';

        $("#deletedCardsContainer").html(html);

        // 为恢复和彻底删除按钮绑定事件
        $(".restore-card").click(function() {
            const cardId = $(this).data("id");
            restoreCard(cardId);
        });

        $(".remove-card").click(function() {
            const cardId = $(this).data("id");
            const cardName = $(this).data("name");
            $("#removeCardName").text(cardName);
            $("#confirmRemoveCard").data("id", cardId);
            $("#removeCardModal").modal("show");
        });
    }

    // 单个录入名片
    $("#addSingleCardBtn").click(function() {
        resetCardForm();
        $("#cardModalTitle").text("添加名片");
        $("#cardModal").modal("show");
    });

    // 批量录入名片
    $("#addBatchCardBtn").click(function() {
        // 清空已有的行，保留一行空白
        $("#batchCardTable tbody").html(
            '<tr>' +
            '<td><input type="text" class="form-control form-control-sm name" required></td>' +
            '<td>' +
            '<select class="form-control form-control-sm gender">' +
            '<option value="">请选择</option>' +
            '<option value="男">男</option>' +
            '<option value="女">女</option>' +
            '</select>' +
            '</td>' +
            '<td><input type="tel" class="form-control form-control-sm phone"></td>' +
            '<td><input type="text" class="form-control form-control-sm organization"></td>' +
            '<td><input type="text" class="form-control form-control-sm position"></td>' +
            '<td><input type="text" class="form-control form-control-sm address"></td>' +
            '<td>' +
            '<button type="button" class="btn btn-sm btn-danger remove-row">删除</button>' +
            '</td>' +
            '</tr>'
        );

        // 绑定删除行事件
        bindRemoveRowEvent();

        $("#batchCardModal").modal("show");
    });

    // 添加一行
    $("#addRow").click(function() {
        const newRow =
            '<tr>' +
            '<td><input type="text" class="form-control form-control-sm name" required></td>' +
            '<td>' +
            '<select class="form-control form-control-sm gender">' +
            '<option value="">请选择</option>' +
            '<option value="男">男</option>' +
            '<option value="女">女</option>' +
            '</select>' +
            '</td>' +
            '<td><input type="tel" class="form-control form-control-sm phone"></td>' +
            '<td><input type="text" class="form-control form-control-sm organization"></td>' +
            '<td><input type="text" class="form-control form-control-sm position"></td>' +
            '<td><input type="text" class="form-control form-control-sm address"></td>' +
            '<td>' +
            '<button type="button" class="btn btn-sm btn-danger remove-row">删除</button>' +
            '</td>' +
            '</tr>';

        $("#batchCardTable tbody").append(newRow);

        // 绑定删除行事件
        bindRemoveRowEvent();
    });

    // 绑定删除行事件
    function bindRemoveRowEvent() {
        $(".remove-row").off("click").on("click", function() {
            // 如果只有一行，不允许删除
            if ($("#batchCardTable tbody tr").length > 1) {
                $(this).closest("tr").remove();
             } else {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>至少保留一行");
            }
        });
    }

    // 保存批量名片
    $("#saveBatchCards").click(function() {
        const cards = [];
        let hasError = false;

        // 收集所有行的数据
        $("#batchCardTable tbody tr").each(function() {
            const name = $(this).find(".name").val().trim();

            // 验证姓名是否填写
            if (!name) {
                hasError = true;
                $(this).find(".name").addClass("is-invalid");
                return;
            } else {
                $(this).find(".name").removeClass("is-invalid");
            }

            const card = {
                folderId: folderId,
                name: name,
                gender: $(this).find(".gender").val(),
                phone: $(this).find(".phone").val(),
                organization: $(this).find(".organization").val(),
                position: $(this).find(".position").val(),
                address: $(this).find(".address").val()
            };

            cards.push(card);
        });

        if (hasError) {
            showToast("error", "<i class='fa fa-times-circle toast-icon'></i>请填写所有必填字段");
            return;
        }

        // 发送请求
        $.ajax({
            url: "/user/businesscard/card/batch-create",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                folderId: folderId,
                cards: cards
            }),
            success: function(response) {
                if (response.success) {
                    $("#batchCardModal").modal("hide");
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>批量创建名片成功");
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>批量创建名片失败：" + response.message);
                }
            },
            error: function() {
                $("#batchCardModal").modal("hide");
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>批量创建名片失败，请稍后重试");
            }
        });
    });

    // 导入名片
    $("#importCardBtn").click(function() {
        $("#importCardModal").modal("show");
    });

    // 提交导入表单
    $("#importCardForm").submit(function(e) {
        e.preventDefault();

        const formData = new FormData(this);

        $.ajax({
            url: "/user/businesscard/card/import",
            type: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    const result = response.importResult;
                    const successCount = result.success;
                    const failRecords = result.fail;

                    let message = "成功导入 " + successCount + " 条记录";

                    if (failRecords && failRecords.length > 0) {
                        message += "，失败 " + failRecords.length + " 条记录";

                        let failDetails = "<ul>";
                        failRecords.forEach(function(record) {
                            failDetails += "<li>第 " + record.rowNum + " 行: " + record.reason + "</li>";
                        });
                        failDetails += "</ul>";

                        $("#importResultDetails").html(failDetails);
                        $("#importResultModal").modal("show");
                    } else {
                        showToast("success", "<i class='fa fa-check-circle toast-icon'></i>" + message);
                        setTimeout(function() {
                            location.reload();
                        }, 1500);
                    }
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>导入名片失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>导入名片失败，请稍后重试");
            }
        });
    });

    // 查看名片
    $(".view-card").click(function() {
        const cardId = $(this).data("id");
        console.log("正在获取名片ID:", cardId); // 调试日志

        $.ajax({
            url: "/user/businesscard/card/search",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                id: cardId
            }),
            success: function(response) {
                console.log("获取到响应:", response); // 调试日志
                if (response.success && response.cards && response.cards.length > 0) {
                    const card = response.cards[0];

                    $("#viewName").text(card.name || "");
                    $("#viewGender").text(card.gender || "");
                    $("#viewPhone").text(card.phone || "");
                    $("#viewEmail").text(card.email || "");
                    $("#viewOrganization").text(card.organization || "");
                    $("#viewPosition").text(card.position || "");
                    $("#viewAddress").text(card.address || "");
                    $("#viewRemark").text(card.remark || "");

                    $("#editFromView").data("id", card.id);

                    $("#viewCardModal").modal("show");
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>获取名片详情失败");
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>获取名片详情失败，请稍后重试");
            }
        });
    });

    // 从查看模态框转到编辑模态框
    $("#editFromView").click(function() {
        const cardId = $(this).data("id");

        $("#viewCardModal").modal("hide");

        // 等待查看模态框关闭后再打开编辑模态框
        $("#viewCardModal").on("hidden.bs.modal", function() {
            editCard(cardId);
            // 解绑事件，防止多次绑定
            $("#viewCardModal").off("hidden.bs.modal");
        });
    });

    // 编辑名片
    $(".edit-card").click(function() {
        const cardId = $(this).data("id");
        editCard(cardId);
    });

    function editCard(cardId) {
        $.ajax({
            url: "/user/businesscard/card/search",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                id: cardId
            }),
            success: function(response) {
                if (response.success && response.cards && response.cards.length > 0) {
                    const card = response.cards[0];

                    $("#cardId").val(card.id);
                    $("#name").val(card.name || "");
                    $("#gender").val(card.gender || "");
                    $("#phone").val(card.phone || "");
                    $("#email").val(card.email || "");
                    $("#organization").val(card.organization || "");
                    $("#position").val(card.position || "");
                    $("#address").val(card.address || "");
                    $("#remark").val(card.remark || "");

                    $("#cardModalTitle").text("编辑名片");
                    $("#cardModal").modal("show");
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>获取名片详情失败");
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>获取名片详情失败，请稍后重试");
            }
        });
    }

    // 保存名片
    $("#saveCard").click(function() {
        if (!$("#cardForm")[0].checkValidity()) {
            // 如果表单验证失败，触发浏览器原生的表单验证
            $("#cardForm")[0].reportValidity();
            return;
        }

        const cardId = $("#cardId").val();
        const isEdit = cardId !== "";

        const cardData = {
            id: cardId,
            folderId: $("#folderId").val(),
            name: $("#name").val(),
            gender: $("#gender").val(),
            phone: $("#phone").val(),
            email: $("#email").val(),
            organization: $("#organization").val(),
            position: $("#position").val(),
            address: $("#address").val(),
            remark: $("#remark").val()
        };

        const url = isEdit ? "/user/businesscard/card/update" : "/user/businesscard/card/create";

        $.ajax({
            url: url,
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(cardData),
            success: function(response) {
                if (response.success) {
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>" + (isEdit ? "更新名片成功" : "创建名片成功"));
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>" + (isEdit ? "更新" : "创建") + "名片失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>" + (isEdit ? "更新" : "创建") + "名片失败，请稍后重试");
            }
        });
    });

    // 删除名片
    $(".delete-card").click(function() {
        const cardId = $(this).data("id");
        const cardName = $(this).data("name");

        $("#deleteCardName").text(cardName);
        $("#confirmDeleteCard").data("id", cardId);
        $("#deleteCardModal").modal("show");
    });

    $("#confirmDeleteCard").click(function() {
        const cardId = $(this).data("id");

        $.ajax({
            url: "/user/businesscard/card/delete/" + cardId,
            type: "POST",
            success: function(response) {
                if (response.success) {
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>删除名片成功");
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>删除名片失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>删除名片失败，请稍后重试");
            }
        });
    });

    // 恢复名片
    function restoreCard(cardId) {
        $.ajax({
            url: "/user/businesscard/card/restore/" + cardId,
            type: "POST",
            success: function(response) {
                if (response.success) {
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>恢复名片成功");
                    // 重新加载已删除的名片列表
                    setTimeout(function() {
                        loadDeletedCards();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>恢复名片失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>恢复名片失败，请稍后重试");
            }
        });
    }

    // 彻底删除名片
    $("#confirmRemoveCard").click(function() {
        const cardId = $(this).data("id");

        $.ajax({
            url: "/user/businesscard/card/remove/" + cardId,
            type: "DELETE",
            success: function(response) {
                if (response.success) {
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>彻底删除名片成功");
                    // 重新加载已删除的名片列表
                    setTimeout(function() {
                        loadDeletedCards();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>彻底删除名片失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>彻底删除名片失败，请稍后重试");
            }
        });
    });

    // 条件查询
    $("#searchCardBtn").click(function() {
        $("#searchCardModal").modal("show");
    });

    $("#searchCardForm").submit(function(e) {
        e.preventDefault();

        const searchParams = {
            folderId: folderId,
            name: $("#searchName").val(),
            gender: $("#searchGender").val(),
            phone: $("#searchPhone").val(),
            organization: $("#searchOrganization").val(),
            position: $("#searchPosition").val(),
            address: $("#searchAddress").val(),
            isDeleted: false
        };
        
        // 保存当前的搜索参数，供导出功能使用
        window.currentSearchParams = searchParams;

        $.ajax({
            url: "/user/businesscard/card/search",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(searchParams),
            success: function(response) {
                if (response.success) {
                    // 关闭搜索模态框
                    $("#searchCardModal").modal("hide");

                    // 显示搜索结果
                    renderSearchResults(response.cards);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>搜索失败：" + response.message);
                }
            },
            error: function() {
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>搜索失败，请稍后重试");
            }
        });
    });

    function renderSearchResults(cards) {
        // 清空表格
        $("#cardTable tbody").empty();

        if (cards.length === 0) {
            $("#cardTable tbody").html('<tr><td colspan="6" class="text-center">没有找到匹配的名片</td></tr>');
            return;
        }

        // 添加导出按钮
        if ($("#exportSearchResults").length === 0) {
            $("#cardTable").before(
                '<div class="mb-3 text-right">' +
                '<button id="exportSearchResults" class="btn btn-outline-success btn-sm">' +
                '<i class="fa fa-download"></i> 导出查询结果</button>' +
                '</div>'
            );
            
            // 绑定导出按钮点击事件
            $("#exportSearchResults").click(function() {
                exportSearchResults();
            });
        }

        // 添加搜索结果
        cards.forEach(function(card) {
            const row =
                '<tr>' +
                '<td>' + (card.name || '') + '</td>' +
                '<td>' + (card.gender || '') + '</td>' +
                '<td>' + (card.phone || '') + '</td>' +
                '<td>' + (card.organization || '') + '</td>' +
                '<td>' + (card.position || '') + '</td>' +
                '<td class="text-right card-actions">' +
                '<button class="btn btn-sm btn-outline-primary btn-card-action view-card" data-id="' + card.id + '" title="查看">' +
                '<i class="fa fa-eye"></i>' +
                '</button> ' +
                '<button class="btn btn-sm btn-outline-secondary btn-card-action edit-card" data-id="' + card.id + '" title="编辑">' +
                '<i class="fa fa-pencil"></i>' +
                '</button> ' +
                '<button class="btn btn-sm btn-outline-danger btn-card-action delete-card" data-id="' + card.id + '" data-name="' + (card.name || '') + '" title="删除">' +
                '<i class="fa fa-trash"></i>' +
                '</button>' +
                '</td>' +
                '</tr>';

            $("#cardTable tbody").append(row);
        });

        // 重新绑定事件
        $(".view-card").click(function() {
            const cardId = $(this).data("id");
            viewCard(cardId);
        });

        $(".edit-card").click(function() {
            const cardId = $(this).data("id");
            editCard(cardId);
        });

        $(".delete-card").click(function() {
            const cardId = $(this).data("id");
            const cardName = $(this).data("name");

            $("#deleteCardName").text(cardName);
            $("#confirmDeleteCard").data("id", cardId);
            $("#deleteCardModal").modal("show");
        });
        
        // 保存最后一次的查询条件
        window.lastSearchParams = window.currentSearchParams;
    }
    
    // 导出查询结果
    function exportSearchResults() {
        if (!window.lastSearchParams) {
            showToast("error", "<i class='fa fa-times-circle toast-icon'></i>没有可用的查询条件");
            return;
        }
        
        showToast("info", "<i class='fa fa-info-circle toast-icon'></i>正在准备导出文件，请稍候...");
        
        // 构建表单数据
        const params = new URLSearchParams();
        for (const key in window.lastSearchParams) {
            params.append(key, window.lastSearchParams[key]);
        }
        
        // 构建导出 URL（使用GET方式）
        const exportUrl = `/user/businesscard/card/export-by-search?${params.toString()}`;
        
        // 使用链接直接下载文件而不是使用fetch
        const downloadLink = document.createElement('a');
        downloadLink.href = exportUrl;
        downloadLink.style.display = 'none';
        document.body.appendChild(downloadLink);
        downloadLink.click();
        setTimeout(() => {
            document.body.removeChild(downloadLink);
            showToast("success", "<i class='fa fa-check-circle toast-icon'></i>导出成功");
        }, 1000);
    }

    // 批量修改
    $("#batchUpdateCardBtn").click(function() {
        $("#batchUpdateModal").modal("show");
    });

    $("#batchUpdateForm").submit(function(e) {
        e.preventDefault();

        // 获取所有选中的卡片ID
        const selectedCardIds = [];
        $(".select-card:checked").each(function() {
            selectedCardIds.push($(this).val());
        });

        if (selectedCardIds.length === 0) {
            showToast("error", "<i class='fa fa-times-circle toast-icon'></i>请至少选择一张名片");
            return;
        }

        const fieldName = $("#updateField").val();
        const newValue = $("#newValue").val();
        
        if (!newValue && newValue !== "") {
            showToast("error", "<i class='fa fa-times-circle toast-icon'></i>请输入新值");
            return;
        }

        // 显示确认信息
        $("#batchUpdateModal").modal("hide");
        showToast("info", "<i class='fa fa-info-circle toast-icon'></i>正在更新，请稍候...");
        
        // 显示调试信息
        console.log("批量更新请求参数:", {
            folderId: folderId,
            cardIds: selectedCardIds,
            fieldName: fieldName,
            newValue: newValue
        });

        $.ajax({
            url: "/user/businesscard/card/batch-update",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
                folderId: folderId,
                cardIds: selectedCardIds,
                fieldName: fieldName,
                newValue: newValue
            }),
            success: function(response) {
                if (response.success) {
                    showToast("success", "<i class='fa fa-check-circle toast-icon'></i>批量更新名片成功");
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                } else {
                    showToast("error", "<i class='fa fa-times-circle toast-icon'></i>批量更新名片失败：" + response.message);
                }
            },
            error: function() {
                $("#batchUpdateModal").modal("hide");
                showToast("error", "<i class='fa fa-times-circle toast-icon'></i>批量更新名片失败，请稍后重试");
            }
        });
    });

    // 重置名片表单
    function resetCardForm() {
        $("#cardId").val("");
        $("#cardForm")[0].reset();
    }
});

// Toast消息提示函数
function showToast(type, message) {
    const toastId = 'toast-' + Date.now();
    const toastClass = type === 'success' ? 'toast-success' : 'toast-error';

    const toast = $(`
        <div class="toast ${toastClass}" id="${toastId}" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000">
            <div class="toast-header">
                <strong class="mr-auto">${type === 'success' ? '成功' : '错误'}</strong>
                <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `);

    $(".toast-container").append(toast);
    $(`#${toastId}`).toast('show');

    // 自动移除已关闭的toast
    $(`#${toastId}`).on('hidden.bs.toast', function() {
        $(this).remove();
    });
}
